<?
/*
	@Author: Ninh The Anh - 
	Email: ninhtheanh@yahooo.com, ninhtheanh@gmail.com
	Phone number: +84983.68.7979
*/
interface DB
{
	public function connect_details($sqlserver, $sqldatabase, $sqluser, $sqlpassword);
	public function set_errors($msg);
	public function get_errors();
	public function is_errors();
	public function disconnect();
	public function query_first($sql);
	public function free_result($query_id=-1);
	public function fetch_row($query_id=-1,$sql=""); 
	public function fetch_array($query_id=-1,$sql=""); 
	public function fetch_object($query_id=-1,$sql=""); 
	public function num_rows($countRows);
	public function query($sql);
	public function query_array($query_array);
	public function get_mysql_insert_id();
	public function get_last_insert_id($tableName);
	public function get_mysql_next_id($tableName);
	public function get_mysql_auto_id($tableName, $fieldID);
	public function get_mysql_affected_rows();
	
	public function get_array($sql);
	public function get_array_no_duplicate($sql);
	public function get_field_value($sql, $fieldName="");
	public function get_mysql_num_fields();
	public function get_mysql_field_name($offset);
	public function get_mysql_field_type($offset);
	public function get_mysql_list_fields($tableName);
	
	public function mysql_insert($table, $toAdd);
	public function mysql_update($table, $update, $where);
	public function mysql_insert_multiple_query($sql, $delimiter = ';');
	public function db_input($str);
	public function db_input_json($str);
}
class DBmysql implements DB
{
	var $server   = DB_HOST;
	var $user     = DB_USER;
	var $pass     = DB_PASSWORD;
	var $database = DB_NAME;
	
	var $state = 0;
	var $record   = array();
	
	var $error   = "";
	var $errno   = 0;
	var $display_errors_msg = true;
	var $display_errors_query = true;
	var $field_table = "";
	var $affected_rows = 0;
	
	var $link_id  = 0;
	var $query_id = 0;
	var $errors = array();
	var $auto_increment_id = "";
	function __construct($defaultConnect = true, $utf8 = true) 
	{
		if($defaultConnect)
		{
			$this->link_id=@mysql_connect($this->server,$this->user,$this->pass);
			if($utf8 == true)
				@mysql_query("SET NAMES utf8", $this->link_id);
			if (!$this->link_id) 
			{
				$this->set_errors("Couldn't connect to mysql");
				$this->state = 0;
			}
			else
			{
				if(!@mysql_select_db($this->database, $this->link_id)) 
				{
					$this->set_errors("Couldn't open database: ".$this->database."");
				}
				$this->state = 1;
			}
		}
  	}
	public function connect_details($sqlserver, $sqldatabase, $sqluser, $sqlpassword, $utf8 = true) 
	{
		$this->server = $sqlserver;
		$this->database = $sqldatabase;
		$this->user = $sqluser;
		$this->pass = $sqlpassword;		
		$this->link_id=@mysql_connect($this->server,$this->user,$this->pass, true);
		if($utf8 == true)
				@mysql_query("SET NAMES utf8", $this->link_id);
		if (!$this->link_id) 
		{
			$this->set_errors("Couldn't connect to mysql");
			exit();
			$this->state = 0;
		}
		else
		{
			if(!@mysql_select_db($this->database, $this->link_id)) 
			{
				$this->set_errors("Couldn't open database: ".$this->database."");
			}
			$this->state = 1;
		}
	}
	function tep_db_prepare_input($string) {  	
		if (is_string($string)) {
		  return trim(stripslashes($string));
		} elseif (is_array($string)) {
		  reset($string);
		  while (list($key, $value) = each($string)) {
			$string[$key] = tep_db_prepare_input($value);
		  }
		  return $string;
		} else {
		  return $string;
		}
	}
	function tep_db_output($string) {
		return htmlspecialchars($string);
	}
	public function query($sql, $addMessage = true) 
	{	
		$this->query_id = @mysql_query($sql, $this->link_id);
		$this->auto_increment_id = @mysql_insert_id($this->link_id);		
		if (!$this->query_id) 
		{
			$strError = "SQL query fail: ". mysql_error($this->link_id);
			if($this->display_errors_query)
				$strError .= " :: " . $sql;				
			$this->set_errors($strError);
			if($this->display_errors_msg && $addMessage)
			{	
				clsErrorMessages::addMessage($strError, "error");				
			}
			$sql = "Insert into log_errors(page_name, error_name) values('".$this->db_input(selfURL())."', '".$this->db_input($strError)."')";
			$this->query_id = @mysql_query($sql,$this->link_id);
		}		
		$this->affected_rows = @mysql_affected_rows($this->link_id);
		
//		$this->writeLogFile($sql);
		
		return $this->query_id;
	}
	public function get_last_insert_id($tableName)
	{
		$sql = "SELECT LAST_INSERT_ID() FROM $table";
    	return mysql_num_rows(mysql_query($sql, $this->link_id));
	}
	public function get_mysql_next_id($tableName)
	{
		$result = mysql_query('SHOW TABLE STATUS LIKE "'.$tableName.'"', $this->link_id);
		$rows = mysql_fetch_assoc($result);
		return $rows['auto_increment'];
	}
	public function get_mysql_auto_id($tableName, $fieldID)
	{
		$query = 'SELECT MAX('.$fieldID.') AS last_id FROM '.$tableName;
		$result = mysql_query($query, $this->link_id);
		$result = mysql_fetch_array($result);
		return $result['last_id']+1; 
	}
	public function get_array($sql)
	{
		$arr = array();
		$rows = $this->query($sql);			
		if($this->affected_rows > 0)
		{
		   while($row = $this->fetch_array($rows))
		   {
		   	  $arr[] = $row;
		   }
		}
		return $arr;	
	}
	public function get_array_no_duplicate($sql)
	{
		$arr = array();
		$rows = $this->query($sql);			
		if($this->affected_rows > 0)
		{
		   while($row = $this->fetch_array($rows))
		   {
			  unset($row[0]);
		   	  $arr[] = $row;
		   }
		}
		return $arr;	
	}
	public function get_field_value($sql, $fieldName="")
	{
		$rows = $this->query($sql);			
		if($this->affected_rows > 0)
		{
		   $row = $this->fetch_array($rows);
		   if($row)
		      return $fieldName != "" ? $row[$fieldName] : $row[0];	
		}
		return NULL;
	}
	public function get_mysql_num_fields()
	{
		return mysql_num_fields($this->query_id);
	}
	public function get_mysql_field_name($offset)
	{
		return mysql_field_name($this->query_id, $offset);		
	}
	public function get_mysql_field_type($offset)
	{
		return mysql_field_type($this->query_id, $offset);		
	}
	public function get_mysql_list_fields($tableName)
	{
		$arr = array();
		$result = mysql_query("SHOW COLUMNS FROM $tableName", $this->link_id);
		if(!$result)
		{
			if($this->display_errors_msg)
				clsErrorMessages::addMessage('Could not run query: ' . mysql_error($this->link_id), "error");	
		}
		else
		{
			if (mysql_num_rows($result) > 0) 
			{
				while ($row = mysql_fetch_assoc($result)) 
				{
					$arr[] = $row;
				}
			}
		}
		return $arr;
	}	
	public function writeLogFile($str)
	{
		if(DB_HOST == "localhost" || DB_HOST == '192.168.1.253')
		{
			return;	
		}
		$sql_temp = trim($str);		
		$sql_temp = substr($sql_temp, 0, 6); 								   
		$sql_temp = strtolower(trim($sql_temp));
		if($sql_temp != "select" && strpos($str, "log_errors") === FALSE)
		{			
			$logTime = date("d-m-Y H:i:s",time());
			$GLOBALS["logfile"]->addTask($logTime . ": " . $str);
			if( mysql_error($this->link_id) != "" )
				$GLOBALS["logfile"]->addTask("SQL query fail: " . mysql_error($this->link_id));				
		}	
	}
	public function query_array($query_array)
	{	
		foreach($query_array as $qa)
		{
			query($qa);
		}		
	}
	public function num_rows($countRows) // or use affected_rows
	{
    	return @mysql_num_rows($countRows);
    }
	public function get_mysql_insert_id()
	{
    	return $this->auto_increment_id;
    }		
	public function fetch_row($query_id=-1,$sql="") 
	{
		if ($query_id!=-1) 
		{
			$this->query_id=$query_id;
		}
		if ( isset($this->query_id) ) 
		{
			$this->record = @mysql_fetch_row($this->query_id);
			$this->field_table = @mysql_field_table($this->query_id,0);//returns table used in query
		}else
		{
			if ( !empty($sql) ) 
			{
				$this->set_errors("Invalid query id (".$this->query_id.") on this query: $sql");
			} else 
			{
				$this->set_errors("Invalid query id ".$this->query_id." specified");
			}
		}	
		return $this->record;
	}
	public function fetch_array($query_id=-1,$sql="") 
	{
		if ($query_id!=-1) 
		{
			$this->query_id=$query_id;
		}
		if ( isset($this->query_id) ) 
		{
			$this->record = @mysql_fetch_array($this->query_id);
			$this->field_table = @mysql_field_table($this->query_id,0);//returns table used in query
		}else
		{
			if ( !empty($sql) ) 
			{
				$this->set_errors("Invalid query id (".$this->query_id.") on this query: $sql");
			} else 
			{
				$this->set_errors("Invalid query id ".$this->query_id." specified");
			}
		}	
		return $this->record;
	}
	public function fetch_object($query_id=-1,$sql="") 
	{
		if ($query_id!=-1) 
		{
			$this->query_id=$query_id;
		}
		if ( isset($this->query_id) ) 
		{
			$this->record = @mysql_fetch_object($this->query_id);
			$this->field_table = @mysql_field_table($this->query_id,0);//returns table used in query
		}else
		{
			if ( !empty($sql) ) 
			{
				$this->set_errors("Invalid query id (".$this->query_id.") on this query: $sql");
			} else 
			{
				$this->set_errors("Invalid query id ".$this->query_id." specified");
			}
		}	
		return $this->record;
	}	
	public function free_result($query_id=-1) 
	{
		if ($query_id!=-1) 
		{
			$this->query_id=$query_id;
		}
		if(!@mysql_free_result($this->query_id)) 
		{
			$this->set_errors("Result set (".$this->query_id.") not freed");
		}
	}
	public function query_first($sql) {
		
		$query_id = $this->query($sql);
		$returnarray=$this->fetch_array($query_id, $sql);
		$this->free_result($query_id);
		return $returnarray;
	}
	public function disconnect() 
	{
		if ($this->state == 1)
		{
			mysql_close($this->link_id);
			$this->state = 0;
			return 1;
		}
		return 0;
	}	
	public function set_errors($msg)
	{	
		$flagAdd = true;
		if(count($this->errors) > 0)
		{
			foreach($this->errors as $err)
			{
				if($err == $msg)
					$flagAdd = false;
			}
		}		
		if($flagAdd)
		{
			$this->errors[] = $msg . "<br>";			
		}
	}
	public function get_errors()
	{
		return $this->errors;
	}
	public function is_errors()
	{
		if($this->errors != NULL && count($this->errors) > 0)
			return true;
		return false;	
	}
	public function mysql_insert($table, $toAdd)
	{
		$fields = implode(array_keys($toAdd), ',');
		$values = "'".implode(array_values($toAdd), "','")."'"; 
		$sql = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';	
		//echo "<br>mysql_insert:" . $sql;					
		return $this->query($sql); 		
	}
	public function mysql_update($table, $update, $where)
	{
		$fields = array_keys($update);
		$values = array_values($update);
		$i = 0;
		$sql = "UPDATE " . $table . " SET ";
		while(isset($fields[$i]))
		{
			if($i!=0)
			{
				$sql.=", ";
			}
			$sql .= $fields[$i] . " = '" . $values[$i] . "'";
			$i++;			
		}
		$sql .= " WHERE " . $where . " LIMIT 1;";
		//echo "<br>mysql_update:" . $sql;		
		return $this->query($sql); 
	}	
	public function mysql_insert_multiple_query($str_sql, $delimiter = ';')
	{
		$result = true;
		$cmdSQL = explode($delimiter, $str_sql);
		foreach($cmdSQL as $sql)
		{
			if($sql != "")
			{
				$this->query($sql);		
				if(mysql_error($this->link_id) != '')
					$result = false;
			}
		}
		return $result;
	}
	// SQl Injection
	function db_input($str) 
	{	
		if (function_exists('mysql_real_escape_string')) 
		{
			$str = stripslashes($str);
			return mysql_real_escape_string($str, $this->link_id);
		} 
		elseif (function_exists('mysql_escape_string')) 
		{
			return mysql_escape_string($str);
		}	
		return addslashes($str);
  }
	 function db_input_json($str) 
	 {	
			if (function_exists('mysql_real_escape_string')) 
			{
				//$str = stripslashes($str);
				return mysql_real_escape_string($str, $this->link_id);
			} 
			elseif (function_exists('mysql_escape_string')) 
			{
				return mysql_escape_string($str);
			}	
			return addslashes($str);
	  }
	function get_mysql_affected_rows() {
		return mysql_affected_rows();
	}	
}

interface DB_i
{
	public function set_errors($msg);
	public function get_errors();
	public function disconnect();
	public function mysql_errors();
	public function get_mysql_insert_id();
	public function query($query_string);

	public function mysql_insert($table, $toAdd);
	public function mysql_update($table, $update, $where);
	public function db_input($string);
	public function get_array($sql);
	public function get_array_no_duplicate($sql);
	public function get_field_value($sql, $column_name = "");
}
class DBmysqli implements DB_i
{
	var $server   = DB_HOST;
	var $user     = DB_USER;
	var $pass     = DB_PASSWORD;
	var $database = DB_NAME;

	var $totalRows = 0;

	var $mysqli  = 0;
	var $errors = array();
	function __construct()
	{
		$this->mysqli = new mysqli($this->server,$this->user,$this->pass,$this->database);
		$this->mysqli->query("SET NAMES 'utf8'");
		if (mysqli_connect_errno())
		{
			$this->set_errors("couldn't connect to mysql: " . mysqli_connect_error());
		}
  	}
	public function query($sql)
	{
		//$this->mysqli->next_result();
		$result = $this->mysqli->query($sql);
		$this->totalRows = $this->mysqli->affected_rows;
		$this->set_errors($this->mysqli->error);
		if (!$result) 
		{			
			$strError = "SQL query fail: ".$this->mysqli->error;			
			$strError .= " :: " . $sql;
			$sql = "Insert into log_errors(page_name, error_name) values('".$this->db_input(selfURL())."', '".$this->db_input($strError)."')";
			$this->query($sql);
		}
		return $result;
	}
	public function multi_query($sql)
	{
		if ($this->mysqli->multi_query($sql))
		{
			return true;
		}
		else
		{
			$this->set_errors($this->mysqli->error);
		}
		return false;
	}
function fetchAll()
{
	  $arrResult = array();
	  if ($result = $this->mysqli->store_result())
	  {
	   while( $row = $result->fetch_row() )
	   {
	    print_r($row);
	    $arrResult[] = $row;
	   }
	   $result->close();
	   if ($this->mysqli->more_results())
	   {
	      $this->mysqli->next_result();
	   }
	  }
	  else
	  {
	   if ($this->mysqli->more_results())
	   {
	    $this->mysqli->next_result();
	    $this->fetchAll();
	   }
	  }
	  return $arrResult;
}
	public function get_mysql_insert_id()
	{
    	return mysqli_insert_id($this->mysqli);
    }
	public function mysql_errors()
	{
		return mysqli_error($this->mysqli);
	}
	public function get_array($sql)
	{
		$arr = array();
		$rows = $this->query($sql);
		if (!$rows)
		{
		}
		else
		{
			if($this->totalRows > 0)
			{
			   while($row = $rows->fetch_array())
			   {
				  $arr[] = $row;
			   }
			}
		}
		return $arr;
	}
	public function get_array_no_duplicate($sql)
	{
		$arr = array();
		$rows = $this->query($sql);
		if (!$rows)
		{
		}
		else
		{
			if($this->totalRows > 0)
			{
			   while($row = $rows->fetch_array())
			   {
				  unset($arr[0]);
				  $arr[] = $row;
			   }
			}
		}
		return $arr;
	}
	public function get_field_value($sql, $column_name = "")
	{
		$arr = array();
		$rows = $this->query($sql);
		$row = $rows->fetch_array();
		if($this->totalRows > 0 && $row)
		{
			if($column_name != "")
				return $row[$column_name];
			else
				return $row[0];
		}
		return "";
	}
	// SQl Injection
	public function db_input($string)
	{
		$string = trim($string);
		$string = str_replace("\\'","'",$string);
		if (function_exists('mysqli_real_escape_string'))
		{
		  return mysqli_real_escape_string($this->mysqli, $string);
		}
		elseif (function_exists('mysqli_escape_string'))
		{
		  return mysqli_escape_string($string);
		}
		return addslashes($string);
   }
	public function disconnect()
	{
		mysqli_close($this->mysqli);
	}
	public function set_errors($msg)
	{
		$flagAdd = $msg != "" ? true : false;
		if(count($this->errors) > 0)
		{
			foreach($this->errors as $err)
			{
				if($err == $msg)
					$flagAdd = false;
			}
		}
		if($flagAdd)
			$this->errors[] = $msg;
	}
	public function get_errors()
	{
		return $this->errors;
	}
	public function mysql_insert($table, $toAdd)
	{
		$fields = implode(array_keys($toAdd), ',');
		$values = "'".implode(array_values($toAdd), "','")."'";
		$sql = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
		//echo "<br>mysql_insert:" . $sql;
		$this->query($sql);
		//-- Example of usage
		//$fields_values = array('id'=>3, 'name'=>'Yo', 'salary' => 5000);
		//mysql_insert('myTable', $tToAdd)
	}
	public function mysql_update($table, $update, $where)
	{
		$fields = array_keys($update);
		$values = array_values($update);
		$i=0;
		$sql="UPDATE ".$table." SET ";
		while($fields[$i])
		{
			if($i!=0)
			{
				$sql.=", ";
			}
			$sql.=$fields[$i]." = '".$values[$i]."'";
			$i++;
		}
		$sql.=" WHERE ".$where." LIMIT 1;";
		//echo "<br>mysql_update:" . $sql;
		$this->query($sql);
		//Example
		// mysql_update('myTable', $anarray, "type = 'main'")
	}
}
?>